#!/usr/bin/env ruby
$LOAD_PATH.unshift File.dirname(__FILE__) + '/../../rspec/lib' # For svn
$LOAD_PATH.unshift File.dirname(__FILE__) + '/../vendor/plugins/rspec/lib' # For rspec installed as plugin
require 'rubygems'
require 'drb/drb'
require 'rbconfig'
require 'spec'

# This is based on Florian Weber's TDDMate

module Spec
  module Runner
    class RailsSpecServer
      def run(args, stderr, stdout)
    	$stdout = stdout
    	$stderr = stderr

        ::Dispatcher.reset_application!
        ::Dependencies.mechanism = :load
        require_dependency('application.rb') unless Object.const_defined?(:ApplicationController)
        load File.dirname(__FILE__) + '/../spec/spec_helper.rb'
    
        ::Spec::Runner::CommandLine.run(args, stderr, stdout, false, true)
      end
    end
  end
end
puts "Loading Rails environment"

ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'dispatcher'

def restart_test_server
  puts "restarting"
  config       = ::Config::CONFIG
  ruby         = File::join(config['bindir'], config['ruby_install_name']) + config['EXEEXT']
  command_line = [ruby, $0, ARGV].flatten.join(' ')
  exec(command_line)
end  

trap("USR2") { restart_test_server } if Signal.list.has_key?("USR2")
puts "Ready"
DRb.start_service("druby://localhost:8989", Spec::Runner::RailsSpecServer.new)
DRb.thread.join